class Snake {
  //表示蛇头的元素
  head: HTMLElement;
  //包括蛇头的所有div HTMLCollection是个集合 特点:实时刷新
  bodies: HTMLCollection;
  //获取蛇的元素
  element: HTMLElement;
  constructor() {
    this.element = document.getElementById("snake")!;
    this.head = document.querySelector("#snake>div") as HTMLElement;
    //获取snake元素下的所有div的
    // document.querySelectorAll("#snake>div");
    this.bodies = this.element.getElementsByTagName("div");
  }
  //获取蛇头的坐标
  get X() {
    return this.head.offsetLeft;
  }
  get Y() {
    return this.head.offsetTop;
  }
  //设置蛇的坐标
  set X(value: number) {
    if (this.X === value) {
      return;
    }
    if (value < 0 || value > 290) {
      //撞墙了
      throw new Error("异常");
    }
    //不允许直接掉头
    if (
      this.bodies[1] &&
      (this.bodies[1] as HTMLElement).offsetLeft === value
    ) {
      if (value > this.X) {
        value = this.X - 10;
      } else {
        value = this.X + 10;
      }
    }
    //移动身体
    this.bodyMove();
    this.head.style.left = value + "px"; //蛇头的最新位置
    console.log(this.head.style.left);

    //检查吃到自己没有
    this.checkHeadBody();
  }
  set Y(value: number) {
    if (this.Y === value) {
      return;
    }
    if (value < 0 || value > 340) {
      //撞墙了
      throw new Error("异常");
    }
    //不允许直接掉头
    if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === value) {
      if (value > this.Y) {
        value = this.Y - 10;
      } else {
        value = this.Y + 10;
      }
    }

    //移动身体
    this.bodyMove();
    this.head.style.top = value + "px"; //蛇头的最新位置
    console.log(this.head.style.top);

    //检查吃到自己没有
    this.checkHeadBody();
  }
  //蛇增加身体的方法
  addBody() {
    //向element中添加div
    this.element.insertAdjacentHTML("beforeend", "<div></div>");
  }
  //蛇身体移动的方法
  bodyMove() {
    /*
     * 后一节移动到前一节的坐标 且从后往前改 */
    //遍历获取所有的身体坐标
    for (let i = this.bodies.length - 1; i > 0; i--) {
      //获取前一位坐标
      let X = (this.bodies[i - 1] as HTMLElement).offsetLeft; //number类型
      let Y = (this.bodies[i - 1] as HTMLElement).offsetTop;
      console.log(X);
      console.log(Y);

      //赋值给后一位坐标
      (this.bodies[i] as HTMLElement).style.left = X + "px";
      (this.bodies[i] as HTMLElement).style.top = Y + "px";
    }
  }
  //检查头与身体是否相撞
  checkHeadBody() {
    //获取所有身体
    for (let i = 3; i < this.bodies.length; i++) {
      let bd = this.bodies[i] as HTMLElement;
      if (this.X === bd.offsetLeft && this.Y === bd.offsetTop) {
        throw new Error("完犊子了");
      }
    }
  }
  //有无身体
}
export default Snake;
